package com.session.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.iman.Confucius.Web7Constants;
import com.iman.Confucius.domain.SessionBean;
import com.iman.Confucius.service.SharedSessionService;
import com.iman.Confucius.util.HoldWebSpringContext;
//import com.iman.Confucius.util.Web7Util;
import com.iman.Confucius.util.Web7Util;
import com.iman.common.util.ConfigUtil;

public class SessionFilter implements Filter {
	private String encoding;
	private  Logger logger = LoggerFactory.getLogger(SessionFilter.class);

	public SessionFilter() {
	}

	public void init(FilterConfig filterconfig) throws ServletException {
		encoding = "utf-8";
	}

	public void doFilter(ServletRequest servletrequest, 	ServletResponse servletresponse, FilterChain filterchain) throws IOException, ServletException {
		
		HttpServletRequest req = (HttpServletRequest) servletrequest;
		HttpSession session = req.getSession();
		HttpServletResponse resp = (HttpServletResponse) servletresponse;

		//获取所有的cookie
		Cookie[] cookies = req.getCookies();
		
		
		String teacherYN= ConfigUtil.getString( "testUserJiaoshi");
		String testEnv= ConfigUtil.getString( "testEnv");
		
		
		
		/***************其他人可以使用这个  学生******************/
		   String  uid = "";
		  String  uidpk = "";
		  //测试环境
		  if(testEnv !=null && testEnv.equalsIgnoreCase( "Y")){
			     uid = "77b0aa0787da5e537fdc9ad1c305a4ac";
			     uidpk = "741e4ef28d954fba5762afe706234319";
			  
			     uid = "2148bb858f4eb9009db1bc0483a0b815";
			     uidpk = "4ad90b6264b15a1b6fc6d4ed05fab464";
			  
			  /******** * 教师*********/
			  if(teacherYN!=null && "Y".equalsIgnoreCase(teacherYN.trim())){
				     uid = "6c137cfc904b15ecbbb86ca71f46a0f9";
				     uidpk = "b202038f2924d1da65322791bdf21801";
				   	
			  }
		  }
		
		 
	 
		  
		if(cookies!=null)
		{
			for(Cookie c:cookies)
			{
				logger.info("cookie name="+c.getName()+"  cookie value:="+c.getValue()+"  all=:"+c.toString());
			
				if(Web7Constants.SHARECOOKIEUSERID .equals(c.getName() )){
					uid = c.getValue();
				}
				
				if(Web7Constants.SHARECOOKIEUSERID_PRIVATEKEY .equals(c.getName() )){
					uidpk = c.getValue();
				}
			}
		}
		
		//TODO	如果   false 说明 失效，或者 错误，需要重新登陆
	  	 boolean  isRightCookie =   Web7Util.checkCookieIdIsOk(uid,uidpk);
	  	 
	  	  
	  	 logger.info("cookie nameuid="+uid+"  cookie uidpk:="+uidpk +"-----------》isRightCookie  result =:"+isRightCookie );
		
		 SessionBean sessionBean = new   SessionBean();
		  
		//  redis 中缓存的KEY SessionBean.USER_SESSION_KEY_PERFIX+sessionkey,  SessionBean.USER_SESSION_SUBKEY_SESSION
		 sessionBean = (SessionBean)session.getAttribute(SessionBean.USER_SESSION_KEY_PERFIX+SessionBean.USER_SESSION_SUBKEY_SESSION );
		 logger.info("登录session  1="+ sessionBean );
		 //当前容器不存在 ，
	     if(sessionBean == null ){
	    	//容器缓存失效
	    	try{
				SharedSessionService sessionUtil =	 	HoldWebSpringContext.getBean("shareusersession", SharedSessionService.class);
				sessionBean = sessionUtil.getSeesion(uid);
			}catch(Exception e){
			  logger.error(e.getMessage(),e);
			}
	     }
	     logger.info("登录session  2="+ sessionBean );
		
		//最后验证是否真的失效
	 	 
		if (sessionBean == null || false==isRightCookie) {
			//TODO	没有登陆  ，返回登陆页面，， 真的 失效了  ，那么重新登陆
		  	 logger.error("重新登录" );
		  	((HttpServletResponse)servletresponse).sendRedirect(ConfigUtil.getString( "notLogin" ) );
		    
		  	return;
		}else{
			//放入内部session 数据量
		    session.setAttribute(SessionBean.USER_SESSION_KEY_PERFIX+SessionBean.USER_SESSION_SUBKEY_SESSION ,sessionBean );
		    logger.info("放入本地session"+ SessionBean.USER_SESSION_KEY_PERFIX+SessionBean.USER_SESSION_SUBKEY_SESSION +"--->"+sessionBean);
		}

		
		
		filterchain.doFilter(servletrequest, servletresponse);
	}

	public void destroy() {

	}
}